package top.cluski.shardingsphere;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import top.cluski.shardingsphere.entity.Course;
import top.cluski.shardingsphere.mapper.CourseMapper;

import javax.annotation.Resource;
import java.util.List;

/**
 * 分片策略为complex时的测试
 */
@SpringBootTest
public class ShardingJDBCTest03 {

    @Resource
    CourseMapper courseMapper;

    /**
     * 当分片键只有cid的时候，但是去查询use_id的条件的时候，会执行全路由，会导致效率比较慢（四个库都会查询）
     * （因为不知道user_id到底是在哪里库中，所有需要执行全路由，全部库都查找一遍）
     * 2022-01-03 22:39:38.742  INFO 10600 --- [           main] ShardingSphere-SQL                       : Logic SQL: SELECT  cid,cname,user_id,cstatus  FROM course
     *
     * 2022-01-03 22:39:38.742  INFO 10600 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: SELECT  cid,cname,user_id,cstatus  FROM course_1
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     * 2022-01-03 22:39:38.742  INFO 10600 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: SELECT  cid,cname,user_id,cstatus  FROM course_2
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     * 2022-01-03 22:39:38.742  INFO 10600 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: SELECT  cid,cname,user_id,cstatus  FROM course_1
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     * 2022-01-03 22:39:38.743  INFO 10600 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: SELECT  cid,cname,user_id,cstatus  FROM course_2
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     *
     *  如果使用了自定义的complex的分片策略的话，可以缩小检索范围
     *  2022-01-03 23:00:44.752  INFO 4160 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: SELECT  cid,cname,user_id,cstatus  FROM course_2
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     * 2022-01-03 23:00:44.752  INFO 4160 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: SELECT  cid,cname,user_id,cstatus  FROM course_2
     *  WHERE (cid BETWEEN ? AND ? AND user_id = ?) ::: [684892194338770944, 684892195014053889, 1007]
     */
    @Test
    public void queryCourseComplex() {
        // select * from course cid between xxx and xxx and user_id = 1007L
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.between("cid", 684892194338770944L, 684892195014053889L);
        wrapper.eq("user_id", 1007L);
        List<Course> courses = courseMapper.selectList(wrapper);
        courses.forEach(System.out::println);
    }
}
